const TOKEN_KEY = 'main_app_token'
const USER_INFO_KEY = 'main_app_user_info'

export const getToken = () => {
  return localStorage.getItem(TOKEN_KEY)
}

export const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token)
  // 同步token到子应用
  if (window.$wujie?.bus) {
    window.$wujie.bus.$emit('main-app:auth-sync', {
      token,
      type: 'token'
    })
  }
}

export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY)
  // 通知子应用清除token
  if (window.$wujie?.bus) {
    window.$wujie.bus.$emit('main-app:auth-sync', {
      token: null,
      type: 'token'
    })
  }
}

export const getUserInfo = () => {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

export const setUserInfo = (userInfo: any) => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
  // 同步用户信息到子应用
  if (window.$wujie?.bus) {
    window.$wujie.bus.$emit('main-app:auth-sync', {
      userInfo,
      type: 'userInfo'
    })
  }
}

export const removeUserInfo = () => {
  localStorage.removeItem(USER_INFO_KEY)
  // 通知子应用清除用户信息
  if (window.$wujie?.bus) {
    window.$wujie.bus.$emit('main-app:auth-sync', {
      userInfo: null,
      type: 'userInfo'
    })
  }
}

export const clearAuth = () => {
  removeToken()
  removeUserInfo()
} 